<script setup lang="ts">

import {onMounted, reactive, ref, watch} from "vue";
import {ElMessage, type FormInstance, type FormRules} from "element-plus";
import {loginAPI} from "@/apis/user";
import {useUserStore} from "@/stores/user";
import {request} from "@/utils/reuqest";
import {json} from "node:stream/consumers";
import {FORMDATA_KEY} from "@/constants";
import {useRouter} from "vue-router";

const fromData = reactive({
  username: '',
  password: '',

})
// 路由器，注意写到 setup 第一级，否则无法正常获取
const router = useRouter();
const formRef = ref<FormInstance>();
//是否记住密码
const remember = ref(false);
//用户协议
const isAgree = ref(false);
const formRules = reactive<FormRules<typeof fromData>>({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 10, message: '用户名长度在3-10个字符'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 12, message: '密码长度在6-12个字符'}
  ],
});
// 侦听数据变化
watch([remember, isAgree], ([val1, val2]) => {
  // 持久化存储
  localStorage.setItem("isRemember", String(val1));
  localStorage.setItem("isAgree", String(val2));
});

const onSubmit = () => {
  if (!isAgree.value) {
    return ElMessage.warning({message: '请勾选用户协议', duration: 1500})
  }
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const res = await loginAPI(fromData)
      // console.log(res.data.token);
      const store = useUserStore()
      store.setToken(res.data.token);
      localStorage.setItem('isRemember', String(remember.value))
      localStorage.setItem('isAgree', String(isAgree))
      localStorage.setItem(FORMDATA_KEY, JSON.stringify(fromData))
      console.log(fromData)
      ElMessage.success({message: '登录成功', duration: 1500});
      // 替换到首页
      await router.replace("/");
    } else {
      // console.log('验证失败');
      ElMessage.error({message: '请输入账号和密码', duration: 1500});
    }
  });
}
// 组件挂载时
onMounted(() => {
  // 获取本地数据，初始化，注意：本地存储保存的是字符串
  remember.value = localStorage.getItem("isRemember") === "true";
  isAgree.value = localStorage.getItem("isAgree") === "true";
  // 如果是记住密码
  if (remember.value) {
    // 获取本地数据
    const formDataStr = localStorage.getItem(FORMDATA_KEY);
    if (formDataStr) {
      // 解析数据
      const data = JSON.parse(formDataStr);
      // 回显到表单上
      fromData.username = data.username;
      fromData.password = data.password;
    }
  }
});

</script>

<template>
  <div class="login_body">
    <div class="bg"/>
    <div class="box">
      <div class="title">智慧园区-登录</div>
      <el-form ref="formRef" :model="fromData" :rules="formRules">
        <el-form-item label="账号" prop="username">
          <el-input v-model="fromData.username" clearable/>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="fromData.password" show-password/>
        </el-form-item>

        <el-form-item prop="remember">
          <el-checkbox v-model="remember">记住我</el-checkbox>
          <el-checkbox v-model="isAgree">用户协议</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="login_btn" @click="onSubmit">登录</el-button>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login_body {
  display: flex;
}

.bg {
  width: 60vw;
  height: 100vh;
  background: url("@/assets/login-bg.svg") no-repeat;
  background-position: right top;
  background-size: cover;
}

.box {
  margin: 200px 10% 0;
  flex: 1;

  .title {
    padding-bottom: 76px;
    font-size: 26px;
    font-weight: 500;
    color: #1e2023;
  }

  ::v-deep {
    .ant-form-item {
      display: flex;
      margin-bottom: 62px;
      flex-direction: column;
    }

    .ant-form-item-label label {
      font-size: 16px;
      color: #8b929d;
    }

    .ant-input,
    .ant-input-password {
      border-radius: 8px;
    }
  }
}

.login_btn {
  width: 100%;
}
</style>
